<?php
require_once('db.php');

define("MAX_FILE_SIZE",102400);
define("MAX_FILES_USER", 2);

function handleUpload($aFiles){
	// Pre-checks. File size and session.
	if (!isset($_SESSION['username']) || !isset($_SESSION['uid'])) return false;
	if ($aFiles['patch']['size'] > 102400) return false; 
	
	$db = getDBResource();
	
	$sUsername = mysql_real_escape_string($_SESSION['username']);
	
	$rQuery = mysql_query("SELECT COUNT(*) FROM user INNER JOIN patch ON user.id = patch.user_id ".
						  "WHERE patch.done = '0' ".
						  "AND user.username = \"".$sUsername."\"");
	
	$iActivePatches = mysql_result($rQuery, 0,0);

	// Check whether user is already at patch limit
	if ($iActivePatches >= MAX_FILES_USER) return false;
	
	$target_path = "patchqueue/";
	
	$sFilename = basename( $_FILES['patch']['name']);
	$target_path = $target_path.$sFilename;
	
	// TODO: Try to apply patch in a trunk. See if it works.
	
	if(move_uploaded_file($_FILES['patch']['tmp_name'], $target_path)) {
		$sFilename = mysql_real_escape_string($sFilename);
		$sUID = mysql_real_escape_string($_SESSION['uid']);
		
		mysql_query("INSERT INTO patch (filename, user_id) VALUES (\"".$sFilename."\",\"".$sUID."\")");
		
		$iID = mysql_insert_id();
		
	    return rename($target_path,$target_path."-id-".$iID);
	    
	} else{
	    return false;
	}
}
?>